package com.rjwh.dingdong.client.fragment.menu;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.loginregist.ThirdPartyLoginActivity;
import com.rjwh.dingdong.client.activity.more.MorePersonDataActivity;
import com.rjwh.dingdong.client.activity.more.MoreSettingActivity;
import com.rjwh.dingdong.client.activity.webbrowser.WebActivity;
import com.rjwh.dingdong.client.adapter.MoreMenuListAdapter;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.BannerData;
import com.rjwh.dingdong.client.bean.localbean.PersonalCenter;
import com.rjwh.dingdong.client.bean.localbean.PersonalCenterMenuData;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.fragment.BaseFragment;
import com.rjwh.dingdong.client.mvp.presenter.impl.MorePersonalCenterPresenter;
import com.rjwh.dingdong.client.mvp.view.MorePersonalCenterView;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.RxBus;
import com.rjwh.dingdong.client.util.UrlUtil;
import com.rjwh.dingdong.client.view.IndicatorHackyViewPager;
import com.rjwh.dingdong.client.view.NoScrollListView;
import com.rjwh.dingdong.client.widget.RoundImageView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 更多
 *
 * @author 王小珂
 * @ClassName MoreFragment
 * @Description 个人中心
 * @date 2015-10-20 上午10:27:54
 * @history 1.YYYY-MM-DD author: description:
 */
@SuppressLint("ValidFragment")
public class MoreFragment extends BaseFragment implements MorePersonalCenterView {

    @BindView(R.id.more_top_img)
    RoundImageView myHead;
    @BindView(R.id.more_user_name_tv)
    TextView useNameTv;
    @BindView(R.id.more_top_root_view)
    RelativeLayout moreTopRootView;
    @BindView(R.id.more_user_account_tv)
    TextView useIdTv;
    @BindView(R.id.more_user_level_img)
    ImageView moreUserLevelImg;
    @BindView(R.id.more_points_btn)
    Button morePointsBtn;
    @BindView(R.id.more_menu_list)
    NoScrollListView moreMenuList;
    @BindView(R.id.loading_layout)
    RelativeLayout loadingLayout;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.more_homework_viewpager)
    IndicatorHackyViewPager moreHomeworkViewpager;

    //    private List<SysLoginBabylistBean> babyList;
    private MorePersonalCenterPresenter presenter;
    private Observable<Integer> observable;
    private MoreMenuListAdapter moreMenuListAdapter;
    private List<PersonalCenterMenuData> menuList = new ArrayList<>();
    private TimeCount time;
    private MyPagerAdapter myPagerAdapter;
    private List<BannerData> mbannerlist = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.more_layou, container, false);
        ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        presenter = new MorePersonalCenterPresenter(getContext(), this);
        startObserver();
//        babyList = MyApplication.db.findAll(SysLoginBabylistBean.class);
        doGetPersonalCenter();
    }

    private void initView() {
        moreMenuList.setFocusable(false);
        moreMenuListAdapter = new MoreMenuListAdapter(getContext());
        moreMenuList.setAdapter(moreMenuListAdapter);
        moreMenuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MoreMenuListAdapter adapter = (MoreMenuListAdapter) parent.getAdapter();
                PersonalCenterMenuData item = adapter.getItem(position);
                String actionurl = item.getActionurl();
                if (!AsStrUtils.isEmpty(actionurl)) {
                    UrlUtil.handelUrl(getContext(), actionurl, true);
                }
            }
        });

        myPagerAdapter = new MyPagerAdapter();
        moreHomeworkViewpager.setAdapter(myPagerAdapter);
        moreHomeworkViewpager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        cancelTimer();
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        if (myPagerAdapter.getCount() > 2) {
                            startTimer();
                        }
                        break;

                    default:
                        break;
                }
                return false;
            }
        });

        List<PersonalCenterMenuData> localMenuList = MyApplication.db.findAll(PersonalCenterMenuData.class);

        if (localMenuList != null && !localMenuList.isEmpty()) {
            LogUtil.d("MoreFragment", "localMenuList.size():" + localMenuList.size());
            updateView(localMenuList);
        }


        List<BannerData> localBannerList = MyApplication.db.findAll(BannerData.class);
        if (localBannerList != null && !localBannerList.isEmpty()) {
            LogUtil.d("MoreFragment", "localBannerList.size():" + localBannerList.size());
            if (localBannerList.size() > 3) {
                if (time == null) {
                    time = new TimeCount(5 * 1000, 1000);// 构造CountDownTimer对象
                }
            }
            myPagerAdapter.addList(localBannerList);
            startTimer();
        }

    }

    private void updateView(List<PersonalCenterMenuData> menuList) {
        moreMenuListAdapter.clearAll();
        moreMenuListAdapter.appendToList(menuList);
        if (MyApplication.spUtil.getBoolPreferenceByParamName(MyApplication.getInstance(),
                LocalConstant.SP_IS_LOGINED)) {
            String userphone = MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.getInstance(), LocalConstant.SP_USERPHONE);
            String imgUrl = MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.getInstance(), LocalConstant.SP_USERIMAGE);
            String userlevel = MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.getInstance(), LocalConstant.SP_USERLEVEL);
            String scorepage = MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.getInstance(), LocalConstant.SP_SCOREPAGEURL);

            //设置了昵称就显示昵称,否则显示帐号(手机号)
            String username = MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.getInstance(), LocalConstant.SP_USERNAME);
            if (!AsStrUtils.isEmpty(username)) {
                useNameTv.setText(username);
            } else {
                if (!AsStrUtils.isEmpty(userphone)) {
                    useNameTv.setText(userphone);
                }
            }
            //设置等级图标
            if (!AsStrUtils.isEmpty(userlevel)) {
                moreUserLevelImg.setVisibility(View.VISIBLE);
                setLevelIcon(moreUserLevelImg, Integer.parseInt(userlevel));
            }
            //设置头像
            if (!AsStrUtils.isEmpty(imgUrl)) {
                Glide.with(this).load(imgUrl).placeholder(R.drawable.icon_defult_avatar).error(R.drawable.icon_defult_avatar).dontAnimate().into(myHead);
            }

            if (!AsStrUtils.isEmpty(scorepage)) {
                morePointsBtn.setVisibility(View.VISIBLE);
            } else {
                morePointsBtn.setVisibility(View.GONE);
            }
        } else {
            changeDefaultView();
        }
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (myPagerAdapter == null) {
                return;
            }
            int count = myPagerAdapter.getCount();
            if (count > 2) { // 多于2个，才循环
                int index = moreHomeworkViewpager.getCurrentItem();
                index = (index + 1) % count;
                moreHomeworkViewpager.setCurrentItem(index, true);
                startTimer();
            } else {
                cancelTimer();
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
        }
    }

    public class MyPagerAdapter extends PagerAdapter {

        private List<BannerData> bannerlist = new ArrayList<>();

        public void addList(List<BannerData> list) {
            if (list != null) {
                bannerlist.clear();
                bannerlist.addAll(list);
                notifyDataSetChanged();
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = new ImageView(getContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if (bannerlist.get(position).getBannerurl() != null) {
                Glide.with(getContext()).load(bannerlist.get(position).getBannerurl()).placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_pic_holder).dontAnimate().into(imageView);
            }
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //banner图跳转
                    String actionurl = bannerlist.get(position).getActionurl();
                    if (actionurl != null) {
                        UrlUtil.handelUrl(getContext(), actionurl, true);
                    }
                }
            });
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return bannerlist == null ? 0 : bannerlist.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    private void doGetPersonalCenter() {
        presenter.doGetPersonalCenter();
    }

    private void setLevelIcon(ImageView imageView, int level) {
        int id = 0;
        switch (level) {
            case 1:
                id = R.drawable.icon_level_v1;
                break;
            case 2:
                id = R.drawable.icon_level_v2;
                break;
            case 3:
                id = R.drawable.icon_level_v3;
                break;
            case 4:
                id = R.drawable.icon_level_v4;
                break;
            case 5:
                id = R.drawable.icon_level_v5;
                break;
            case 6:
                id = R.drawable.icon_level_v6;
                break;
            default:
                break;
        }
        imageView.setImageResource(id);
    }

    @Override
    public void showLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void showErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadData(PersonalCenter personalcenter, List<List<PersonalCenterMenuData>> cells) {
        List<PersonalCenterMenuData> localMenuList = MyApplication.db.findAll(PersonalCenterMenuData.class);

        MyApplication.spUtil.setStrPreference(MyApplication.getInstance(), LocalConstant.SP_USERLEVEL, personalcenter.getUserlevel());
        MyApplication.spUtil.setStrPreference(MyApplication.getInstance(), LocalConstant.SP_SCOREPAGEURL, personalcenter.getScorepage());
        menuList.clear();
        LogUtil.d("MorePersonalCenter", "loadData");
        if (localMenuList != null && !localMenuList.isEmpty()) {
            LogUtil.d("MorePersonalCenter", "db.deleteAll");
            MyApplication.db.deleteAll(PersonalCenterMenuData.class);
        }
        for (List<PersonalCenterMenuData> cell : cells) {
            for (PersonalCenterMenuData personalCenterMenuData : cell) {
                LogUtil.d("MorePersonalCenter", "db.save");
                MyApplication.db.save(personalCenterMenuData);
            }
            menuList.addAll(cell);
        }
        updateView(menuList);
    }

    @Override
    public void loadLocalList() {
        List<PersonalCenterMenuData> localMenuList = MyApplication.db.findAll(PersonalCenterMenuData.class);
        if (localMenuList != null && !localMenuList.isEmpty()) {
            hideLoadingView();
            hideErrorView();
        } else {
            showErrorView();
        }
    }

    @Override
    public void laodBannerData(List<BannerData> bannerlist) {
        List<BannerData> localBannerList = MyApplication.db.findAll(BannerData.class);
        LogUtil.d("MorePersonalCenter", "laodBannerData");
        if (localBannerList != null && !localBannerList.isEmpty()) {
            LogUtil.d("MorePersonalCenter", "db.deleteAll");
            MyApplication.db.deleteAll(BannerData.class);
        }
        for (BannerData bannerData : bannerlist) {
            LogUtil.d("MorePersonalCenter", "bannerdb.save");
            MyApplication.db.save(bannerData);
            mbannerlist.addAll(bannerlist);
        }
        if (mbannerlist.size() > 3) {
            if (time == null) {
                time = new TimeCount(5 * 1000, 1000);// 构造CountDownTimer对象
            }
        }
        myPagerAdapter.addList(bannerlist);
        startTimer();
    }

    @OnClick({R.id.more_top_root_view, R.id.more_title_right_btn, R.id.more_points_btn})
    public void onClick(View view) {
        boolean isLogined = MyApplication.spUtil.getBoolPreferenceByParamName(getContext(),
                LocalConstant.SP_IS_LOGINED);
        if (isLogined) {
            switch (view.getId()) {
                case R.id.more_top_root_view:
                    startActivity(new Intent(getActivity(), MorePersonDataActivity.class));
                    break;
                case R.id.more_title_right_btn:
                    startActivity(new Intent(getActivity(), MoreSettingActivity.class));
                    break;
                case R.id.more_points_btn:
                    String scorepage = MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_SCOREPAGEURL);
                    String webUrl = UrlUtil.getWebUrl(getContext(), scorepage);
                    WebActivity.startActivity(getContext(), webUrl);
                    break;
            }
        } else {
            ThirdPartyLoginActivity.startActivity(getContext());
        }
    }

    @OnClick(R.id.btn_refresh)
    public void onClick() {
        showLoadingView();
        doGetPersonalCenter();
    }

    private void startObserver() {
        observable = RxBus.get().register(LocalConstant.RX__POST_LOGIN_UPDATE_UI, Integer.class);
        observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                               @Override
                               public void call(Integer type) {
                                   if (type == 1) {
                                       //登录后请求网络
                                       LogUtil.e("morefragment", "type = 1,登录成功后刷新ui");
                                       doGetPersonalCenter();
                                   } else if (type == 2) {
                                       //退出登录后,显示默认未登录视图
                                       LogUtil.e("morefragment", "type = 2,退出登录成功后刷新ui");
                                       changeDefaultView();
                                   }
                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {
                                   LogUtil.d("MoreFragment", throwable.getMessage());
                               }
                           }
                );
    }

    private void changeDefaultView() {
        useNameTv.setText("未登录");
        myHead.setImageResource(R.drawable.icon_defult_avatar);
        moreUserLevelImg.setVisibility(View.GONE);
        morePointsBtn.setVisibility(View.GONE);
    }

    private void startTimer() {
        if (time != null) {
            time.start();
        }
    }

    private void cancelTimer() {
        if (time != null) {
            time.cancel();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.detachView();
        cancelTimer();
        RxBus.get().unregister(LocalConstant.RX__POST_LOGIN_UPDATE_UI, observable);
    }

}
